<?php

namespace App\Http\Controllers\Manage;

use App\Model\Role;
use App\Model\Rule;
use App\Model\Table;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Manage;
use Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Validator;

class RuleController extends Controller
{
    protected static $field = [
        'id' => '编号',
        'create_time' => '创建时间',
        'update_time' => '更新时间',
        'create_user' => '创建人',
        'update_user' => '更新人',
        'rank' => '权重',
        'role_id' => '角色',
        'table_id' => '表明'
    ];

    /**
     * @var int 数据表id
     */
    public $table_id = 4;

    /**
     * CaseController constructor.
     */
    public function __construct()
    {
        parent::__construct($this->table_id);

    }
    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        #判断权限
        if($this->rule['view'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        #检测是否存在参数
        $role_id = $request->input('role');

        $obj = new Rule;
        $check_time = Input::get('check_time');
        $category = Input::get('category');
        $keyword = Input::get('keyword');
        $time = Input::get('create_time');
        $type = Input::get('type');
        $code = Input::get('code');
        if(Input::has('category') && Input::has('keyword')) {
            if(Input::get('category') === 'create_user' || Input::get('category') === 'update_user') {
                $user = Manage::select('id')->where('username','like',"%$keyword%")->get();
                $obj = $obj->whereIn(Input::get('category'),$user);
            }
            else if(Input::get('category') === 'role_id') {
                $role = Role::select('id')->where('name','like',"%$keyword%")->get();
                $obj = $obj->whereIn('role_id',$role);
            }
            else if(Input::get('category') === 'table_id') {
                $table = Table::select('id')->where('name','like',"%$keyword%")->get();
                $obj = $obj->whereIn('table_id',$table);
            }
            else {
                $obj = $obj->where(Input::get('category'),'like',"%$keyword%");
            }
        }
        if(Input::has('check_time')) {
            $start_time = date("Y-m-d 00:00:00",strtotime(substr($time , 0 , 10)));
            $end_time = date("Y-m-d 23:59:59",strtotime(substr($time,-10)));
            $obj = $obj->whereBetween('create_time',[$start_time,$end_time]);
        }
        //升降排序
        if(Input::has('type') && Input::has('code')) {
            if($code == 0) {
                $obj = $obj->orderBy($type,'asc');
            }
            if($code == 1) {
                $obj = $obj->orderBy($type,'desc');
            }
        }

        #获取权限列表
        if($role_id){
            $data = $obj->where('role_id',$role_id)->orderBy('role_id','asc')->paginate(10);
        }else{
            $data = $obj->orderBy('role_id','asc')->paginate(10);
        }
        $field = self::$field;
        return view('manage/system/rule/index', compact('data','field','check_time','category','keyword','time','type','code'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        #判断权限
        if($this->rule['add'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        #获取角色信息
        $role = Role::where('status',1)->get();
        #获取数据库表信息
        $table = Table::all();
        return view('manage.system.rule.create',compact('role','table'));
    }

    public function store(Request $request)
    {
        #判断权限
        if($this->rule['add'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
//
        $input = $request->only('user_id','role_id','table_id','view','add','update','delete');
        $rule = [
            'role_id' => 'required',
            'table_id' => 'required',
            'view' => 'required',
            'add' => 'required',
            'update' => 'required',
            'delete' => 'required',
        ];
        $message = [
            'required' => ':attribute 不能为空'
        ];
        $attributes = [
            'role_id' => '角色',
            'table_id' => '数据库表',
            'view' => '查看权限',
            'add' => '创建权限',
            'update' => '修改权限',
            'delete' => '删除权限',
        ];
        $validator = Validator::make($input, $rule, $message, $attributes);
        if($validator->fails()) {
            $warnings = $validator->messages()->first();
            return redirect()->back()->withInput()->withErrors($warnings);
        }else{
            #查找重复
            if(Rule::where('role_id',$request['role_id'])->where('table_id',$request['table_id'])->first()){
                return redirect()->back()->withInput()->withErrors('该角色对应的数据表权限已添加，请勿重复添加！');
            }
            $res = Rule::insert([
                'create_user' => $request->input('user_id'),
                'role_id'=>$request->input('role_id'),
                'table_id'=>$request->input('table_id'),
                'view'=>$request->input('view'),
                'add'=>$request->input('add'),
                'update'=>$request->input('update'),
                'delete'=>$request->input('delete')
            ]);
            if($res){
                return Redirect::to("manage/rule");
            }else{
                return redirect()->back()->withInput()->withErrors('添加失败！');
            }
        }
    }
    /**
     * @param Request $request
     * @return array
     */
    public function setRule(Request $request)
    {
        #判断权限
        if($this->rule['update'] == 0){
            return [
                'code' => 101,
                'msg' => '权限不足！'
            ];
        }
        $field = $request->input('field');
        $param = $request->input('param');
        $id = $request->input('id');
        $user_id = $request->input('user_id');
        if (empty($field) || ($param != 0 && $param != 1) || empty($id)) {
            return [
                'code' => 101,
                'msg' => '参数错误！'
            ];
        }
        $param == 1 ? $data = 0 : $data = 1;
        $res = Rule::where('id', $id)->update([$field => $data,'update_user'=>$user_id]);
        if ($res) {
            return [
                'code' => 100,
                'msg' => '授权成功！'
            ];
        } else {
            return [
                'code' => 101,
                'msg' => '授权失败！'
            ];
        }
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return array
     */
    public function destroy()
    {
        #判断权限
        if($this->rule['delete'] == 0){
            return [
                'code' => 101,
                'msg' => '权限不足！'
            ];
        }
        $id = Input::get('id');
        $res = Rule::where('id',$id)->delete();
        if($res){
            return [
                'code' => 100,
                'msg' => '删除成功！'
            ];
        }else{
            return [
                'code' => 101,
                'msg' => '删除失败！'
            ];
        }
    }
}
